{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# spread_robots_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/spread_robots_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/spread_robots_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "maximize the minimum of pairwise distances between n robots in a square space.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "from typing import Sequence\n",
    "from ortools.sat.colab import flags\n",
    "from google.protobuf import text_format\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "_NUM_ROBOTS = flags.define_integer(\"num_robots\", 8, \"Number of robots to place.\")\n",
    "_ROOM_SIZE = flags.define_integer(\n",
    "    \"room_size\", 20, \"Size of the square room where robots are.\"\n",
    ")\n",
    "_PARAMS = flags.define_string(\n",
    "    \"params\",\n",
    "    \"num_search_workers:16, max_time_in_seconds:20\",\n",
    "    \"Sat solver parameters.\",\n",
    ")\n",
    "\n",
    "\n",
    "def spread_robots(num_robots: int, room_size: int, params: str) -> None:\n",
    "    \"\"\"Optimize robots placement.\"\"\"\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # Create the list of coordinates (x, y) for each robot.\n",
    "    x = [model.new_int_var(1, room_size, f\"x_{i}\") for i in range(num_robots)]\n",
    "    y = [model.new_int_var(1, room_size, f\"y_{i}\") for i in range(num_robots)]\n",
    "\n",
    "    # The specification of the problem is to maximize the minimum euclidian\n",
    "    # distance between any two robots. Unfortunately, the euclidian distance\n",
    "    # uses the square root operation which is not defined on integer variables.\n",
    "    # To work around, we will create a min_square_distance variable, then we make\n",
    "    # sure that its value is less than the square of the euclidian distance\n",
    "    # between any two robots.\n",
    "    #\n",
    "    # This encoding has a low precision. To improve the precision, we will scale\n",
    "    # the domain of the min_square_distance variable by a constant factor, then\n",
    "    # multiply the square of the euclidian distance between two robots by the same\n",
    "    # factor.\n",
    "    #\n",
    "    # we create a scaled_min_square_distance variable with a domain of\n",
    "    # [0..scaling * max euclidian distance**2] such that\n",
    "    #   forall i:\n",
    "    #     scaled_min_square_distance <= scaling * (x_diff_sq[i] + y_diff_sq[i])\n",
    "    scaling = 1000\n",
    "    scaled_min_square_distance = model.new_int_var(\n",
    "        0, 2 * scaling * room_size**2, \"scaled_min_square_distance\"\n",
    "    )\n",
    "\n",
    "    # Build intermediate variables and get the list of squared distances on\n",
    "    # each dimension.\n",
    "    for i in range(num_robots - 1):\n",
    "        for j in range(i + 1, num_robots):\n",
    "            # Compute the distance on each dimension between robot i and robot j.\n",
    "            x_diff = model.new_int_var(-room_size, room_size, f\"x_diff{i}\")\n",
    "            y_diff = model.new_int_var(-room_size, room_size, f\"y_diff{i}\")\n",
    "            model.add(x_diff == x[i] - x[j])\n",
    "            model.add(y_diff == y[i] - y[j])\n",
    "\n",
    "            # Compute the square of the previous differences.\n",
    "            x_diff_sq = model.new_int_var(0, room_size**2, f\"x_diff_sq{i}\")\n",
    "            y_diff_sq = model.new_int_var(0, room_size**2, f\"y_diff_sq{i}\")\n",
    "            model.add_multiplication_equality(x_diff_sq, x_diff, x_diff)\n",
    "            model.add_multiplication_equality(y_diff_sq, y_diff, y_diff)\n",
    "\n",
    "            # We just need to be <= to the scaled square distance as we are\n",
    "            # maximizing the min distance, which is equivalent as maximizing the min\n",
    "            # square distance.\n",
    "            model.add(scaled_min_square_distance <= scaling * (x_diff_sq + y_diff_sq))\n",
    "\n",
    "    # Naive symmetry breaking.\n",
    "    for i in range(1, num_robots):\n",
    "        model.add(x[0] <= x[i])\n",
    "        model.add(y[0] <= y[i])\n",
    "\n",
    "    # Objective\n",
    "    model.maximize(scaled_min_square_distance)\n",
    "\n",
    "    # Creates a solver and solves the model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    if params:\n",
    "        text_format.Parse(params, solver.parameters)\n",
    "    solver.parameters.log_search_progress = True\n",
    "    status = solver.solve(model)\n",
    "\n",
    "    # Prints the solution.\n",
    "    if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:\n",
    "        print(\n",
    "            f\"Spread {num_robots} with a min pairwise distance of\"\n",
    "            f\" {math.sqrt(solver.objective_value / scaling)}\"\n",
    "        )\n",
    "        for i in range(num_robots):\n",
    "            print(f\"robot {i}: x={solver.value(x[i])} y={solver.value(y[i])}\")\n",
    "    else:\n",
    "        print(\"No solution found.\")\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "\n",
    "    spread_robots(_NUM_ROBOTS.value, _ROOM_SIZE.value, _PARAMS.value)\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
